'use client';

import { ReactNode, useState, useEffect } from 'react';
import Link from 'next/link';
import { useAuth } from '../contexts/AuthContext';
import { usePathname, useRouter } from 'next/navigation';
import { 
  IconHome, 
  IconApple, 
  IconSearch, 
  IconClipboardList, 
  IconHeartHandshake,
  IconUser
} from '@tabler/icons-react';

interface LayoutProps {
  children: ReactNode;
}

interface NavItem {
  path: string;
  label: string;
  icon: React.ReactNode;
  requireAuth: boolean;
}

export default function Layout({ children }: LayoutProps) {
  const { user, loading: authLoading, logout } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const [mounted, setMounted] = useState(false);

  // 等待客户端挂载完成
  useEffect(() => {
    setMounted(true);
  }, []);

  // 如果还没挂载完成，返回一个占位结构
  if (!mounted) {
    return (
      <div className="min-h-screen bg-[#f9f9fa]">
        <header className="bg-white shadow-sm fixed w-full z-10 h-16" />
        <main className="max-w-7xl mx-auto px-4 py-8 pt-24">
          <div className="bg-white rounded-lg shadow-sm">
            {children}
          </div>
        </main>
      </div>
    );
  }

  const navItems: NavItem[] = [
    { 
      path: '/diet-recommend', 
      label: '饮食推荐', 
      icon: <IconApple className="w-5 h-5 stroke-2" />,
      requireAuth: true
    },
    { 
      path: '/nutrition-search', 
      label: '营养信息查询', 
      icon: <IconSearch className="w-5 h-5 stroke-2" />,
      requireAuth: false
    },
    { 
      path: '/diet-record', 
      label: '饮食记录', 
      icon: <IconClipboardList className="w-5 h-5 stroke-2" />,
      requireAuth: true
    },
    { 
      path: '/health-advice', 
      label: '健康建议', 
      icon: <IconHeartHandshake className="w-5 h-5 stroke-2" />,
      requireAuth: true
    }
  ];

  const isActive = (path: string) => pathname === path;

  const handleNavClick = (e: React.MouseEvent<HTMLAnchorElement>, requireAuth: boolean) => {
    if (requireAuth && !user) {
      e.preventDefault();
      const currentPath = encodeURIComponent(pathname);
      router.push(`/login?redirect=${currentPath}`);
    }
  };

  return (
    <div className="min-h-screen bg-[#f9f9fa]">
      {/* 顶部导航栏 */}
      <header className="bg-white shadow-sm fixed w-full z-10">
        <div className="max-w-7xl mx-auto px-4">
          <div className="flex justify-between h-16">
            {/* Logo 和主导航 */}
            <div className="flex items-center space-x-8">
              <Link href="/" className="text-xl font-bold flex items-center space-x-2">
                <IconApple className="w-6 h-6 stroke-2" />
                <span>健康饮食推荐</span>
              </Link>
              
              {/* 主导航 */}
              <nav className="hidden md:flex items-center space-x-4">
                {navItems.map((item) => (
                  <Link
                    key={item.path}
                    href={item.path}
                    onClick={(e) => handleNavClick(e, item.requireAuth)}
                    className={`flex items-center space-x-2 px-3 py-2 rounded-md transition-colors
                      ${isActive(item.path)
                        ? 'bg-blue-500 text-white'
                        : 'hover:bg-gray-50 text-gray-700 hover:text-blue-600'}`}
                  >
                    {item.icon}
                    <span>{item.label}</span>
                    {item.requireAuth && !user && (
                      <span className="ml-1 text-xs text-gray-400">
                        (需登录)
                      </span>
                    )}
                  </Link>
                ))}
              </nav>
            </div>

            {/* 用户相关 */}
            <div className="flex items-center space-x-4">
              {user ? (
                <div className="flex items-center space-x-4">
                  <Link 
                    href="/profile"
                    className="text-sm text-gray-700 hover:text-blue-600 flex items-center space-x-2 group"
                  >
                    <div className="bg-gray-100 p-1.5 rounded-full group-hover:bg-blue-50">
                      <IconUser className="w-5 h-5 stroke-2 group-hover:text-blue-600" />
                    </div>
                    <span className="group-hover:text-blue-600">{user.email}</span>
                  </Link>
                  <button
                    onClick={() => {
                      router.push('/');
                      logout();
                    }}
                    className="btn-primary bg-red-600 hover:bg-red-700"
                  >
                    退出
                  </button>
                </div>
              ) : (
                <div className="space-x-4">
                  <Link 
                    href={`/login?redirect=${encodeURIComponent(pathname)}`} 
                    className="btn-primary"
                  >
                    登录
                  </Link>
                  <Link href="/register" className="btn-primary">
                    注册
                  </Link>
                </div>
              )}
            </div>
          </div>

          {/* 移动端导航菜单 */}
          <div className="md:hidden pb-4">
            <nav className="flex flex-col space-y-2">
              {navItems.map((item) => (
                <Link
                  key={item.path}
                  href={item.path}
                  onClick={(e) => handleNavClick(e, item.requireAuth)}
                  className={`flex items-center space-x-2 px-3 py-2 rounded-md transition-colors
                    ${isActive(item.path)
                      ? 'bg-blue-500 text-white'
                      : 'hover:bg-gray-50 text-gray-700 hover:text-blue-600'}`}
                >
                  {item.icon}
                  <span>{item.label}</span>
                  {item.requireAuth && !user && (
                    <span className="ml-auto text-xs text-gray-400">
                      需登录
                    </span>
                  )}
                </Link>
              ))}
            </nav>
          </div>
        </div>
      </header>

      {/* 页面内容 */}
      <main className="max-w-7xl mx-auto px-4 py-8 pt-24">
        <div className="bg-white rounded-lg shadow-sm">
          {children}
        </div>
      </main>
    </div>
  );
} 